<script setup lang="ts">
import { onMounted, ref, reactive } from 'vue'
import { Icon } from '@/components/Icon'
import {
  ElCard,
  ElTable,
  ElTableColumn,
  ElSelect,
  ElOption,
  ElForm,
  ElFormItem,
  ElInput,
  ElInputNumber,
  ElButton,
  ElMessage
} from 'element-plus'
import { Dialog } from '@/components/Dialog'
import { useIcon } from '@/hooks/web/useIcon'
import { RetrieveVariety } from '@/api/sysmanage/variety'
import { RetrieveIndex } from '@/api/syscontent/datlib'
import {
  RetrieveBlock,
  RetrieveGroup,
  RetrieveGroupIndex,
  CreateBlock,
  CreateGroup,
  CreateGroupIndex
} from '@/api/syscontent/flexdatalib'
import {
  BlockItem,
  BlockData,
  GroupItem,
  GroupData,
  IndexData,
  IndexItem
} from './types/flexDatalib'
const plusIcon = useIcon({ icon: 'system-uicons:plus' })
const varietyList = ref<Array<{ code: string; name: string }>>([])
const indexForSelect = ref<Array<{ id: number; name: string; plat: string }>>([])
const blockData = reactive<BlockData>({
  blocks: []
})
const editBlockDig = reactive({
  isShow: false,
  showTitle: '新建类别',
  confirmButtonText: '确定保存',
  confirmLoading: false
})
const initBlockItem = { id: undefined, block_name: '', sort_num: 1 }
const editBlockItem = reactive<BlockItem>(JSON.parse(JSON.stringify(initBlockItem)))

const groupData = reactive<GroupData>({
  blockId: undefined,
  groups: []
})
const editGroupDig = reactive({
  isShow: false,
  showTitle: '新建组别',
  confirmButtonText: '确定保存',
  confirmLoading: false
})
const initGroupItem: GroupItem = { id: -1, index_name: '', frequency: '日', sort_num: 1 }
const editGroupItem = reactive<GroupItem>(JSON.parse(JSON.stringify(initGroupItem)))

const indexData = reactive<IndexData>({
  groupId: undefined,
  varietyEn: undefined,
  indexList: []
})
const editIndexDig = reactive({
  isShow: false,
  showTitle: '添加数据',
  confirmButtonText: '确定保存',
  confirmLoading: false
})
const initIndexItem: IndexItem = {
  id: -1,
  index_id: '',
  index_name: '',
  block_group_id: -1,
  variety_en: '',
  note: ''
}
const editIndexItem = reactive<IndexItem>(JSON.parse(JSON.stringify(initIndexItem)))

const blockSelectChange = (bid: number) => {
  groupData.blockId = bid
  loadGroupList()
}
const toCreateNewBlock = () => {
  Object.assign(editBlockItem, initBlockItem)
  editBlockItem.id = -1
  editBlockDig.confirmButtonText = '确定保存'
  editBlockDig.showTitle = '新建类别'
  editBlockDig.isShow = true
}
const toShowEditBlock = (block: BlockItem) => {
  Object.assign(editBlockItem, block)
  ElMessage.error('暂不支持修改')
  return
  editBlockItem.block_name = block.block_name
  editBlockDig.showTitle = '修改类别'
  editBlockDig.confirmButtonText = '确定修改'
  editBlockDig.isShow = true
}
const toConfirmSaveBlock = () => {
  if (editBlockItem.id && editBlockItem.id > 0) {
    //
  } else {
    editBlockDig.confirmLoading = true
    CreateBlock(editBlockItem)
      .then((res) => {
        ElMessage.success(res.message)
        editBlockDig.isShow = false
        editBlockDig.confirmLoading = false
        loadBlockList()
      })
      .catch(() => {
        editBlockDig.confirmLoading = false
      })
  }
}
const toCreateNewGroup = () => {
  editGroupItem.id = -1
  editGroupDig.confirmButtonText = '确定保存'
  editGroupDig.showTitle = '新建组别'
  editGroupDig.isShow = true
}
const toShowEditGroup = () => {
  ElMessage.error('暂不支持修改')
}
const toConfirmSaveGroup = () => {
  if (!groupData.blockId) return
  if (editGroupItem.id && editGroupItem.id > 0) {
    //
  } else {
    editGroupDig.confirmLoading = true
    const groupItem = {
      block_id: groupData.blockId,
      index_name: editGroupItem.index_name,
      frequency: editGroupItem.frequency,
      unit: ''
    }
    CreateGroup(groupItem)
      .then((res) => {
        ElMessage.success(res.message)
        editGroupDig.isShow = false
        editGroupDig.confirmLoading = false
        loadGroupList()
      })
      .catch(() => {
        editGroupDig.confirmLoading = false
      })
  }
}

const groupSelectChange = (gid: number) => {
  indexData.groupId = gid
  loadIndexList()
}
const varietySelectChange = (v: string) => {
  indexData.varietyEn = v
  loadIndexList()
}
const toShowEditGroupIndex = () => {
  ElMessage.error('暂不支持修改组内指标')
}
const toAddNewIndex = () => {
  if (!indexData.groupId || !indexData.varietyEn) return
  Object.assign(editIndexItem, initIndexItem)
  editIndexItem.id = -1
  editIndexItem.block_group_id = indexData.groupId
  editIndexItem.variety_en = indexData.varietyEn
  editIndexDig.confirmButtonText = '确定添加'
  editIndexDig.showTitle = '添加新数据指标'
  editIndexDig.isShow = true
}
const indexSelectChange = (index_id: number) => {
  editIndexItem.index_id = index_id
  for (let i: number = 0; i < indexForSelect.value.length; i++) {
    if (indexForSelect.value[i].id === index_id) {
      editIndexItem.index_name = indexForSelect.value[i].name
      break
    }
  }
}
const toConfirmSaveGroupIndex = () => {
  editIndexDig.confirmLoading = true
  if (editIndexItem.id && editIndexItem.id > 0) {
    //
  } else {
    CreateGroupIndex(editIndexItem)
      .then((res) => {
        ElMessage.success(res.message)
        editIndexDig.isShow = false
        editIndexDig.confirmLoading = false
        loadIndexList()
      })
      .catch(() => {
        editIndexDig.confirmLoading = false
      })
  }
}

const loadBlockList = () => {
  RetrieveBlock().then((res) => {
    // console.log(res)
    blockData.blocks = res.data.blocks
  })
}
const loadGroupList = () => {
  groupData.groups = []
  if (!groupData.blockId) return
  RetrieveGroup(groupData.blockId).then((res) => {
    // console.log(res)
    groupData.groups = res.data.groups
  })
}
const loadIndexList = () => {
  indexData.indexList = []
  if (!indexData.groupId) return
  RetrieveGroupIndex(indexData.groupId, indexData.varietyEn).then((res) => {
    indexData.indexList = res.data.index_list
  })
}
const remoteQueryIndex = (kw: string) => {
  RetrieveIndex({ kw, page: 1, page_size: 100 }).then((res) => {
    indexForSelect.value = res.data.data.rows
    console.log(res)
  })
}

onMounted(() => {
  loadBlockList()
  RetrieveVariety({ kw: '', scope: 'S05', code: '' }).then((res) => {
    varietyList.value = res.data.data
  })
})
</script>
<template>
  <div class="page-view">
    <ElCard shadow="hover">
      <template #header>
        <div class="card-header">
          <Icon icon="uil:setting" />
          <div class="name">1、数据类别</div>
        </div>
      </template>
      <div>
        <div class="actions">
          <div class="right-action">
            <ElButton type="primary" :icon="plusIcon" @click="toCreateNewBlock">新建</ElButton>
          </div>
        </div>
        <ElTable border strip style="margin-top: 10px" :data="blockData.blocks">
          <ElTableColumn prop="id" label="ID" width="80">
            <template #default="scope">
              <div class="edit-column" @click="toShowEditBlock(scope.row)">
                <Icon class="edit-icon" icon="svg-icon:box-edit" />
                <div class="row-id">{{ scope.row.id }}</div>
              </div>
            </template>
          </ElTableColumn>
          <ElTableColumn prop="block_name" label="名称" />
          <ElTableColumn prop="sort_num" label="顺序" width="70" />
        </ElTable>
      </div>
    </ElCard>
    <div class="gap"></div>
    <ElCard shadow="hover">
      <template #header>
        <div class="card-header">
          <Icon icon="uil:setting" />
          <div class="name">2、类别分组</div>
        </div>
      </template>
      <div>
        <div class="actions">
          <ElSelect
            v-model="groupData.blockId"
            clearable
            placeholder="选择一个数据类别"
            @change="blockSelectChange"
          >
            <ElOption
              v-for="b in blockData.blocks"
              :key="b.id"
              :value="b.id"
              :label="b.block_name"
            />
          </ElSelect>
          <div class="right-action">
            <ElButton
              type="primary"
              :icon="plusIcon"
              :disabled="groupData.blockId ? groupData.blockId < 0 : true"
              @click="toCreateNewGroup"
              >新建</ElButton
            >
          </div>
        </div>
        <ElTable border stripe style="margin-top: 10px" :data="groupData.groups">
          <ElTableColumn label="ID" width="80">
            <template #default="scope">
              <div class="edit-column" @click="toShowEditGroup">
                <Icon class="edit-icon" icon="svg-icon:box-edit" />
                <div class="row-id">{{ scope.row.id }}</div>
              </div>
            </template>
          </ElTableColumn>
          <ElTableColumn prop="index_name" label="组别名称" />
          <ElTableColumn prop="frequency" label="频率" width="70" />
          <ElTableColumn prop="sort_num" label="顺序" width="70" />
        </ElTable>
      </div>
    </ElCard>
    <div class="gap"></div>
    <ElCard shadow="hover">
      <template #header>
        <div class="card-header">
          <Icon icon="uil:setting" />
          <div class="name">3、组内指标</div>
        </div>
      </template>
      <div>
        <div class="actions">
          <ElSelect
            v-model="indexData.groupId"
            clearable
            placeholder="选择一个数据组"
            @change="groupSelectChange"
          >
            <ElOption
              v-for="g in groupData.groups"
              :key="g.id"
              :value="g.id"
              :label="g.index_name"
            />
          </ElSelect>
          <ElSelect
            v-model="indexData.varietyEn"
            clearable
            style="margin-left: 10px"
            placeholder="选择品种"
            @change="varietySelectChange"
          >
            <ElOption v-for="v in varietyList" :key="v.code" :value="v.code" :label="v.name" />
          </ElSelect>
          <div class="right-action">
            <ElButton
              type="primary"
              :icon="plusIcon"
              :disabled="!indexData.groupId || !indexData.varietyEn"
              @click="toAddNewIndex"
              >添加</ElButton
            >
          </div>
        </div>
        <ElTable border stripe style="margin-top: 10px" :data="indexData.indexList">
          <ElTableColumn prop="id" label="ID" width="80">
            <template #default="scope">
              <div class="edit-column" @click="toShowEditGroupIndex">
                <Icon class="edit-icon" icon="svg-icon:box-edit" />
                <div class="row-id">{{ scope.row.id }}</div>
              </div>
            </template>
          </ElTableColumn>
          <ElTableColumn prop="index_name" label="数据名称" />
          <ElTableColumn prop="plat_id" label="数据ID" width="150" />
          <ElTableColumn prop="unit" label="单位" width="100" />
          <ElTableColumn prop="variety_en" label="品种" width="80" />
        </ElTable>
      </div>
    </ElCard>
    <Dialog v-model="editBlockDig.isShow" :title="editBlockDig.showTitle">
      <ElForm label-width="70" label-position="right">
        <ElFormItem label="类别名称">
          <ElInput v-model="editBlockItem.block_name" placeholder="输入类别的名称" />
        </ElFormItem>
        <ElFormItem label="排序">
          <ElInputNumber v-model="editBlockItem.sort_num" :min="1" />
        </ElFormItem>
      </ElForm>
      <template #footer>
        <ElButton @click="editBlockDig.isShow = false">取消</ElButton>
        <ElButton type="primary" :loading="editBlockDig.confirmLoading" @click="toConfirmSaveBlock">
          {{ editBlockDig.confirmButtonText }}
        </ElButton>
      </template>
    </Dialog>
    <Dialog v-model="editGroupDig.isShow" :title="editGroupDig.showTitle">
      <ElForm>
        <ElFormItem label="组别名称">
          <ElInput v-model="editGroupItem.index_name" placeholder="输入组别的名称" />
        </ElFormItem>
        <ElFormItem label="数据频率">
          <ElInput v-model="editGroupItem.frequency" placeholder="数据频率为:日、周、月、季、年" />
        </ElFormItem>
        <ElFormItem label="排序数字">
          <ElInputNumber v-model="editGroupItem.sort_num" :min="1" />
        </ElFormItem>
      </ElForm>
      <template #footer>
        <ElButton @click="editGroupDig.isShow = false">取消</ElButton>
        <ElButton type="primary" :loading="editGroupDig.confirmLoading" @click="toConfirmSaveGroup">
          {{ editGroupDig.confirmButtonText }}
        </ElButton>
      </template>
    </Dialog>
    <Dialog v-model="editIndexDig.isShow" :title="editIndexDig.showTitle">
      <ElForm>
        <ElFormItem label="搜索指标">
          <ElSelect
            v-model="editIndexItem.index_id"
            filterable
            remote
            placeholder="关键字搜索指标"
            style="width: 100%"
            :remote-method="remoteQueryIndex"
            @change="indexSelectChange"
          >
            <ElOption
              v-for="item in indexForSelect"
              :key="item.id"
              :value="item.id"
              :label="`${item.name} (${item.plat})`"
            />
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="新的名称">
          <ElInput v-model="editIndexItem.index_name" placeholder="重新命名数据名称" />
        </ElFormItem>
        <ElFormItem label="备注信息">
          <ElInput v-model="editIndexItem.note" placeholder="备注信息" />
        </ElFormItem>
      </ElForm>
      <template #footer>
        <ElButton @click="editIndexDig.isShow = false">取消</ElButton>
        <ElButton
          type="primary"
          :loading="editIndexDig.confirmLoading"
          @click="toConfirmSaveGroupIndex"
        >
          {{ editIndexDig.confirmButtonText }}
        </ElButton>
      </template>
    </Dialog>
  </div>
</template>
<style scoped lang="less">
.page-view {
  .gap {
    height: 10px;
  }
  .card-header {
    display: flex;
    align-items: center;

    .name {
      color: #f86e00;
      font-weight: 700;
      margin-left: 5px;
    }
  }
  .edit-column {
    display: flex;
    align-items: center;
    cursor: pointer;
    .edit-icon {
      margin-right: 5px;
    }
  }
  .actions {
    display: flex;
    align-items: center;
    .right-action {
      margin-left: auto;
    }
  }
}
</style>
